package com.jiuli_shoppingpro.chat;

import com.alibaba.fastjson.JSON;
import com.jiuli_shoppingpro.chat.pojo.Message;
import jakarta.servlet.http.HttpSession;
import jakarta.websocket.OnClose;
import jakarta.websocket.OnMessage;
import jakarta.websocket.OnOpen;
import jakarta.websocket.Session;
import jakarta.websocket.server.ServerEndpoint;
import jakarta.websocket.server.ServerEndpointConfig;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;

import java.io.IOException;
import java.util.Map;
import java.util.Set;
import java.util.concurrent.ConcurrentHashMap;

@Slf4j
@ServerEndpoint(value = "/chat", configurator = GetHttpSessionConfig.class)
@Component
public class ChatEndPoint {
    private HttpSession httpSession;

    //共享在线用户的信息
    private static final Map<String, Session> onlineUsers = new ConcurrentHashMap<>();

    @OnOpen
    public void onOpen(Session session, ServerEndpointConfig serverEndpointConfig){
        //获取httpSession
        httpSession = (HttpSession) serverEndpointConfig.getUserProperties().get(HttpSession.class.getName());//这一步还不是很理解
        String username = (String) httpSession.getAttribute("username");

        //保存session信息
        onlineUsers.put(username, session);

        //广播信息，告诉前端当前在线人数
        broadcastAllUser(username+"被上线");
    }

    private void broadcastAllUser(String message){
        try {
            //遍历map集合
            Set<Map.Entry<String, Session>> entriedSet = onlineUsers.entrySet();

            for (Map.Entry<String, Session> entry : entriedSet) {
                //获取session对象进行发送消息
                Session session = entry.getValue();
                session.getBasicRemote().sendText(message);
            }
        }catch (Exception e){
            log.info("服务器出现异常");
        }
    }

    @OnMessage
    public void onMessage(String message){
        //将json格式数据转化为对象
        Message msg = JSON.parseObject(message, Message.class);
        //获取信息
        String toName = msg.getToName();
        String toMsg = msg.getMsg();
        //发送消息给对方（也不是持久化存储呀）
        Session session = onlineUsers.get(toName);

        try {
            session.getBasicRemote().sendText(httpSession.getAttribute("user") +"给"+toName+"发送了消息："+ message);
        } catch (IOException e) {
            throw new RuntimeException(e);
        }


    }

    @OnClose
    public void onClose(Session session){
        //从onlineUsers中剔除该用户
        String username = (String) httpSession.getAttribute("user");
        onlineUsers.remove(username);

        //广播信息
        broadcastAllUser(username+"被剔除");


    }


}











